package com.trainoo.novel.crawler;

import com.trainoo.novel.constant.NovelConstant;
import com.trainoo.novel.model.Book;
import com.trainoo.novel.model.Chapter;
import com.trainoo.novel.util.UrlDownLoader;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.*;

/**
 * ZW 转码适配器
 */
@Component
public class ZwNovelCrawler extends NovelCrawlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(ZwNovelCrawler.class);

    @Value("${base.url.zw}")
    private String BASE_URL;

    @Value("${search.url.zw}")
    private String SEARCH_URL;

    @Override
    public Book crawlBookInfo(String bookId){
        // 返回结果集
        Book book = new Book();
        // 解析网页
        Document doc = UrlDownLoader.download(BASE_URL + "/book/" + bookId + "/");
        // 小说名、作者、简介
        Element main = doc.getElementById("maininfo");
        String mainInfo = main.html();
        String bookName = main.getElementsByTag("h1").html();
        book.setBookName(bookName);
        book.setMainInfo(mainInfo);
        // 保存章节信息
        Elements dd = doc.getElementById("list").getElementsByTag("dl").get(0).getElementsByTag("dd");
        List<Chapter> chapList = new ArrayList<>();
        for (int i = 0; i < dd.size(); i++) {
            String chapName = dd.get(i).child(0).html();
            String chapUrl = dd.get(i).child(0).attr("href");
            Chapter chap = new Chapter(chapName, chapUrl);
            chapList.add(chap);
        }
        book.setChapters(chapList);
        logger.info("正在加载图书[{}]详情", bookName);
        return book;
    }

    @Override
    public Chapter readChapter(String url){
        Document doc =  UrlDownLoader.download(BASE_URL + "/book/" + url);
        String title = doc.title();
        title = title.substring(0, title.lastIndexOf("-"));
        String content = doc.getElementById("content").html();
        String prev = doc.getElementsByClass("bottem1").get(0).child(0).attr("href");
        String chap = doc.getElementsByClass("bottem1").get(0).child(1).attr("href");
        String next = doc.getElementsByClass("bottem1").get(0).child(2).attr("href");

        Chapter chapter = new Chapter();
        chapter.setPreUrl(prev);
        chapter.setChapMain(chap);
        chapter.setNextUrl(next);
        chapter.setChapName(title);
        chapter.setContent(content);
        logger.info("正在加载内容[{}]", title);

        return chapter;
    }

    @Override
    public List<Chapter> hotBookList(){
        Document doc = UrlDownLoader.download(BASE_URL);
        Elements aList = doc.getElementsByTag("a");
        List<Chapter> hotList = new ArrayList<>();
        Set<String> urls = new HashSet<>();
        for (int i = 0; i < aList.size(); i++) {
            String html = aList.get(i).html();
            String href = aList.get(i).attr("href");
            if (!html.contains("img") && !href.contains(".html") && href.contains("/book")){
                // 使用set去重
                if(urls.add(href)){
                    hotList.add(new Chapter(html, href));
                }
            }
        }
        return hotList;
    }

    @Override
    public List<Book> searchBook(Map<String, String> contentMap) {
        String url = SEARCH_URL + formatUri(contentMap.get(NovelConstant.KEY_WORD), contentMap.get(NovelConstant.PAGE));
        Document doc = UrlDownLoader.download(url);
        Elements elemList = doc.getElementsByClass("result-list").first().getElementsByClass("result-item");
        List<Book> resultList = new ArrayList<>();
        String pageInfo = doc.getElementsByClass("search-result-page-main").first().html().replace("search.php", "searchPhp");
        contentMap.put("pageInfo", pageInfo);
        for (Element element : elemList){
            String bookDesc = element.getElementsByClass("result-game-item-desc").text();
            String authName = element.getElementsByClass("result-game-item-info-tag").first().text();
            Elements aList = element.getElementsByTag("a");
            String bookUrl = aList.get(1).attr("href");
            bookUrl = bookUrl.substring(bookUrl.lastIndexOf("/book/") + 5);
            String bookName = aList.get(1).attr("title");
            String newUrl = aList.get(2).attr("href");
            String newName = aList.get(2).text();
            Book book = new Book();
            book.setBookDesc(bookDesc);
            book.setAuthName(authName.replace("作者：", ""));
            book.setBookUrl("/book/" + bookUrl);
            book.setBookName(bookName);
            book.setNewName(newName);
            book.setNewUrl("/book/" + bookUrl + newUrl.substring(newUrl.lastIndexOf("/") + 1));
            resultList.add(book);
        }
        return resultList;
    }

    private String formatUri(String keyWord, String page) {
        try {
            int p = Integer.parseInt(page);
            if (p == 0){
                return MessageFormat.format("?keyword={0}", URLEncoder.encode(keyWord, "utf-8"));
            }
            return MessageFormat.format("?keyword={0}&page={1}", URLEncoder.encode(keyWord, "utf-8"), page);
        } catch (Exception e) {
            logger.error("格式化搜索url出现异常，keyWord={}, page={}, e={}", keyWord, page, e);
        }
        return "";
    }
}
